import React, { Component } from "react";
import { Container } from "./style";
import {
  Button,
  Modal,
  Layout,
  Menu,
  Dropdown,
  Input,
  Table,
  Space,
  Upload,
  message,
} from "antd";
import "antd/dist/antd.css";

// import connect from './connect'
// @connect
// 表格
import { UploadOutlined } from '@ant-design/icons';
import { useContext, useState, useEffect, useRef } from 'react';
import { Popconfirm, Form } from 'antd';
const EditableContext = React.createContext();
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef();
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async (e) => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
  }
  return <td {...restProps}>{childNode}</td>;
};
const props = {
  name: 'file',
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};
class index extends Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '序号',
        dataIndex: 'key',
      },
      {
        title: '供应商名称',
        dataIndex: 'school',
        // width: '30%',
        // editable: true,
      },
      {
        title: '供应商编码',
        dataIndex: 'Name',
      },
      {
        title: '联系人',
        dataIndex: 'people',
      },
      {
        title: '联系人电话',
        dataIndex: 'Code',
      },

      {
        title: '地址',
        dataIndex: 'address',
      },
      {
        title: '状态',
        dataIndex: 'method',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.key)}>
              <a>删除</a>
              <div></div>
            </Popconfirm>

          ) : null,
      },
    ];
    this.state = {
      dataSource: [
        {
          key: "1",
          school: "北京巡洋有限公司",
          Name: "fty68j",
          Code: 15149325076,
          people: "张俊",
          address: "北京市昌平区沙河镇海特光电园区302",
          method: '启用'
        },
        {
          key: "2",
          school: "京东商城",
          Name: "fthu56",
          Code: 13349323213,
          people: "陈岐",
          address: "北京市大兴区亦庄",
          method: '启用'
        },
        {
          key: "3",
          school: "淘宝商城",
          Name: "dvnu57nu",
          Code: 13364253076,
          people: "姚珂",
          address: "北京市昌平区沙河镇海特光电园区302",
          method: '启用'
        },
        {
          key: "4",
          school: "小米有品",
          Name: "crvny",
          Code: 11493235076,
          people: "陈张婷",
          address: "北京市大兴区亦庄",
          method: '启用'
        },
        {
          key: "5",
          school: "豌豆公主",
          Name: "4679y6h",
          Code: 13349325457,
          people: "熊朝丹",
          address: "北京市海淀区中关村软件园",
          method: '启用'
        },
        {
          key: "6",
          school: "小红书",
          Name: "4y6h",
          Code: 13349325076,
          people: "申梦月",
          address: "北京市海淀区安宁庄路",
          method: '启用'
        },
      ],
      count: 6,
    };
  }

  handleDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.key !== key),
    });
  };
  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count + 1,
      school: "天猫国际",
      Name: "cgn45",
      Code: 321124,
      people: "熊朝丹",
      address: "西办公楼403",
      method: '启用'
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    this.setState({
      dataSource: newData,
    });
  };
  state = {
    loading: false,
    visible: false,
  };
  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = () => {
    this.setState({ loading: true });
    setTimeout(() => {
      this.setState({ loading: false, visible: false });
    }, 3000);
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };
  // componentDidMount(){
  //   // 在这里发送每个页面获取数据的请求
  //   // this.props.setSwiperData()
  // }
  render() {
    const { visible, loading } = this.state;
    const { Header, Content } = Layout;
    const menu = (
      <Menu>
        <Menu.Item>
          <a target="_blank" rel="noopener noreferrer">
            启用
          </a>
        </Menu.Item>
        <Menu.Item>
          <a target="_blank" rel="noopener noreferrer">
            禁用
          </a>
        </Menu.Item>
      </Menu>
    );
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Container>
          <div className='header'>
            <div className="left">
              <li>
              <Button type="primary" onClick={this.showModal}>
                供应商档案
              </Button>
              <Modal
                visible={visible}
                title="Title"
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                footer={[
                  <Button key="back" onClick={this.handleCancel}>
                   取消
                  </Button>,
                  <Button
                    key="submit"
                    type="primary"
                    loading={loading}
                    onClick={this.handleOk}
                  >
                    确认
                  </Button>,
                ]}
              >
                <div>
                  <p>供应商名称: <Input placeholder="请输入供应商名称" /></p>
                  <p>供应商编码: <Input placeholder="供应商编码" /></p>
                  <p>联系人: <Input placeholder="请输入联系人" /></p>
                  <p>联系电话: <Input placeholder="联系电话" /></p>
                  <p>地址: <Input placeholder="请输入地址" /></p>
                  <div>状态:
                    <p>
                      <Dropdown overlay={menu} placement="bottomCenter" arrow>
                        <Button>启用</Button>
                      </Dropdown>
                    </p>
                  </div>
                  <div>资质文件:
                    <p> 
                      <Upload {...props}>
                          <Button>选择文件</Button>
                      </Upload>
                    </p>
                  </div>
                </div>
              </Modal>
              </li>
              <li>
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>导入</Button>
              </Upload>,
              </li>
            </div>
            <ul className="right">
              <li>
                <Dropdown overlay={menu} placement="bottomCenter" arrow>
                  <Button>启用</Button>
                </Dropdown>
              </li>
              <li>
                <Input placeholder="供应商名称" style={{ width: 150 }} />
              </li>
              <li>
                <Button type="primary">查询</Button>
              </li>
              <li>
                <Button
                  onClick={this.handleAdd}
                  type="primary"
                  style={{
                    marginBottom: 16,
                  }}
                >
                  增加
        </Button>
              </li>
            </ul>
          </div>
          <div className="last">
            <div className="main">
              <div>
                <Table
                  components={components}
                  rowClassName={() => 'editable-row'}
                  bordered
                  dataSource={dataSource}
                  columns={columns}
                />
              </div>
            </div>
          </div>
      </Container>
    );
  }
}
export default index;


